﻿using System.Windows;
using System.Windows.Controls;
using System.Collections.Specialized;
using System.Configuration;
using ScanSnap.Domain.JSON;
using ScanSnap.Util;
using System.Net;
using ScanSnap.Wpf.WpfWindow;
using System.Windows.Input;


namespace ScanSnap.Wpf.WpfPage
{
    /// <summary>
    /// Interaction logic for LoginPage.xaml
    /// </summary>
    public partial class LoginPage : Page
    {
        private readonly string SERVER_URL = ConfigurationManager.AppSettings["url"];
        private static LoginPage instance;

        private LoginPage()
        {
            InitializeComponent();
        }

        public static LoginPage Instance
        {
            get
            {
                if (instance == null)
                {
                    instance = new LoginPage();
                }

                return instance;
            }
        }

        private void SignInButton_Click(object sender, RoutedEventArgs e)
        {
            SignIn();
        }

        private void SignIn()
        {
            using (WebClient client = new WebClient())
            {

                SignInJSON signIn;
                try
                {
                    signIn = JsonService.SignIn(UsernameText.Text, PasswordText.Password);
                    if (signIn.Status.Equals("SUCCESS"))
                    {
                        MainApplicationPage MainAppPage = MainApplicationPage.Instance(signIn.User);
                        //LoginWindow.Instance.Hide();// Close();
                        MainWindow.Instance.ContentFrame.Content = MainAppPage;
                        ErrorLabel.Content = "";
                    }
                    else if (signIn.Status.Equals("NOT_FOUND"))
                    {
                        ErrorLabel.Content = "ユーザ名とパスワードが無効です。";
                    }
                    else if (signIn.Status.Equals("DB_ERROR"))
                    {
                        ErrorLabel.Content = "ユーザ名とパスワードが無効です。";
                    }
                    else if (signIn.Status.Equals("SUCCESS"))
                    {
                        ErrorLabel.Content = "ユーザ名とパスワードが無効です。";
                    }
                }
                catch (WebException)
                {
                    ErrorLabel.Content = "Cannot connect to the server, try again...";
                }
            }
        }

        private void CancelButton_Click(object sender, RoutedEventArgs e)
        {
            //System.Windows.Application.Current.Shutdown();
            UsernameText.Text = "";
            PasswordText.Password = "";
        }

        private void EnterClicked(object sender, System.Windows.Input.KeyEventArgs e)
        {
            if (e.Key == Key.Return)
            { //Keys.Enter
                SignIn();
                e.Handled = true;
            }
        }
    }
}
